package com.htwy.core.controller;

import com.htwy.core.config.WebappConfig;
import com.htwy.core.model.Menu;
import com.htwy.ext.BaseController;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;

public class MenuController extends BaseController<Menu> {

    @Override
    protected Menu dao() {
        return Menu.dao;
    }

    @Override
    public boolean beforeSave(Menu entity) {
//        if(StrKit.isBlank(entity.getParentId())){
//            renderJson(Ret.fail().set("msg","必须拥有父组织机构"));
//            return false;
//        }
//
        Menu parent = dao().findById(entity.getParentId());
        entity.setLevel(parent.getLevel() + 1);
        if (StrKit.isBlank(entity.getUuid())) {
            entity.setChildrenCount(0);
        }
        if (entity.getSerial() == null){
            entity.setSerial(getNextSerial(entity.getParentId()));
        }
        return true;
    }

    @Override
    public boolean afterSave(Menu entity) {
        dao().updateChildrenCount(entity.getParentId());
        return true;
    }

    private Integer getNextSerial(String parentId) {
        Integer maxSerial = dao().getMaxSerialByParentId(parentId);
        return maxSerial != null ? maxSerial + 1 : 1;
    }

    @Override
    public void batchDelete() {
        String[] pkArray = getParaValues(dao().getPrimaryKey() + WebappConfig.getConfig().get("idsSuffix", "s"));
        Menu menu = dao().findById(pkArray[0]);
        Integer result = dao().deleteByPks(pkArray);
        dao().updateChildrenCount(menu.getParentId());
        renderJson(Ret.ok().set("data", result));

    }
}